<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2018/10/1
 * Time: 下午4:28
 */

namespace common\utils;

use yii;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\base\Object;

class ImageUpload extends Object
{
    /**
     * @param \yii\base\Model $model 实例化模型
     * @param string $field <input name="$field">
     * @param array $config 上传文件配置
     *[
     * 'uploadPath'='', 上传路径
     * 'fileSize' = (int),
     * 'allowType'= [],
     * ]
     * 在实例化前要配置@uploads
     *
     * @return array
     */
    const TYPE_NOT_ALLOW = 0;
    const SIZE_OVER_FLOWER = 1;
    const SAVE_FALSE = 2;
    const FILE_NOT_EXITS = 3;
    const PATH_NOT_RIGHT = 4;
    const SUCCESS = 5;
    public $error;
    public $status;
    public $filename = '';
    private $msg = ['上传的文件类型不允许', '上传的文件大小超过给定值', '文件保存失败', '未上传文件', '上传路径错误', '上传成功'];

    public function upload($model, $field, $config = [])
    {
        // 文件上传路径

        $folder = isset($config['uploadPath']) ? '/' . $config['uploadPath'] . '/' : '/';
        $path   = Yii::getAlias('@uploads') . $folder;


        if (FileHelper::createDirectory($path) === true) { //路径存在或创建成功
            $files = UploadedFile::getInstance($model, $field); //获取文件
            if ($files) {
                $fileSize  = isset($config['fileSize']) ? $config['fileSize'] : 50 * 1024 * 1024; // 默认50M
                $allowType = isset($config['allowType']) ? $config['allowType'] : ['jpg', 'jpeg', 'gif', 'png', 'bmp'];

                // 扩展名
                $ext = $files->getExtension();
                if (empty($ext)) {
                    $ext_tmp = explode('/', $files->type);
                    $ext     = isset($ext_tmp[1]) ? $ext_tmp[1] : '';
                }
                if ( ! in_array(strtolower($ext), $allowType)) {

                    return ['code' => -1, 'msg' => $this->uploadFail(self::TYPE_NOT_ALLOW), 'data' => []];
                }

                // 文件大小
                if ($files->size > $fileSize) {

                    return ['code' => -1, 'msg' =>$this->uploadFail(self::SIZE_OVER_FLOWER), 'data' => []];
                }
                // 文件名
                $fileName       = uniqid() . '.' . $ext;
                $this->filename = isset($config['uploadPath'])?$config['uploadPath'].'/'.$fileName:''.$fileName;
                if ($files->saveAs($path . $fileName)) {

                    return ['code' => 0, 'msg' => $this->uploadSuccess(), 'data' => $folder . $fileName];
                } else {

                    return ['code' => -1, 'msg' => $this->uploadFail(self::SAVE_FALSE), 'data' => []];
                }
            } else {
                return ['code' => -1, 'msg' => $this->uploadFail(self::FILE_NOT_EXITS), 'data' => []];
            }
        } else {
            return ['code' => -1, 'msg' =>$this->uploadFail(self::PATH_NOT_RIGHT), 'data' => []];
        }

    }

    private function uploadFail($errorType)
    {
        $this->status = false;

        return $this->error = $this->msg[$errorType];
    }
    private function uploadSuccess(){
        $this->status = true;
        return $this->msg[self::SUCCESS];
    }



}